﻿using AutoMapper;
using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Extensions;
using DTcms.Core.Common.Helper;
using DTcms.Core.DBFactory.Database;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using DTcms.Core.Model.ViewModels;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace DTcms.Core.Services
{
    /// <summary>
    /// 会员充值接口实现
    /// </summary>
    public class MemberRechargeService : BaseService, IMemberRechargeService
    {
        private readonly IMemberGroupService _memberGroupService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        public MemberRechargeService(IDbContextFactory contentFactory,
            IMemberGroupService memberGroupService, IUserService userService, IMapper mapper) : base(contentFactory)
        {
            _memberGroupService = memberGroupService;
            _userService = userService;
            _mapper = mapper;
        }

        /// <summary>
        /// 根据条件获取一条记录
        /// </summary>
        public async Task<MemberRecharge?> QueryAsync(Expression<Func<MemberRecharge, bool>> funcWhere,
            WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = await _context.Set<MemberRecharge>()
                .Include(x => x.Collection)
                .FirstOrDefaultAsync(funcWhere);
            return result;
        }

        /// <summary>
        /// 根据条件获取列表
        /// </summary>
        public async Task<IEnumerable<MemberRecharge>> QueryListAsync(int top, Expression<Func<MemberRecharge, bool>> funcWhere,
            string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = _context.Set<MemberRecharge>()
                .Include(x => x.Collection).Where(funcWhere).OrderByBatch(orderBy);//调用Linq扩展类排序
            if (top > 0) result = result.Take(top);//等于0显示所有数据
            return await result.ToListAsync();
        }

        /// <summary>
        /// 根据条件获取分页列表
        /// </summary>
        public async Task<PaginationList<MemberRecharge>> QueryPageAsync(int pageSize, int pageIndex,
            Expression<Func<MemberRecharge, bool>> funcWhere, string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = _context.Set<MemberRecharge>()
                .Include(x => x.Collection).Where(funcWhere).OrderByBatch(orderBy);//调用Linq扩展类排序
            return await PaginationList<MemberRecharge>.CreateAsync(pageIndex, pageSize, result);
        }

        /// <summary>
        /// 新增一条记录
        /// </summary>
        public async Task<PaymentCollection> AddAsync(MemberRechargeEditDto modelDto, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            //检查会员是否存在
            var memberModel = await _context.Set<Members>()
                .Include(x => x.User)
                .FirstOrDefaultAsync(x => x.UserId == modelDto.UserId);
            if (memberModel == null)
            {
                throw new ResponseException("会员账户不存在或已删除");
            }
            //检查支付方式是否存在
            var paymentModel = await _context.Set<SitePayment>().Include(x => x.Payment).FirstOrDefaultAsync(x => x.Id == modelDto.PaymentId);
            if (paymentModel == null || paymentModel.Payment == null)
            {
                throw new ResponseException("支付方式不存在或已删除");
            }

            //新增一条充值记录
            List<MemberRecharge> rechargeList = new()
            {
                new()
                {
                    UserId = memberModel.UserId,
                    UserName = memberModel.User?.UserName,
                    Amount = modelDto.Amount
                }
            };
            //新增一条收款单
            PaymentCollection model = new()
            {
                UserId = modelDto.UserId.GetValueOrDefault(),
                TradeNo = $"RN{UtilConvert.GetGuidToNumber()}",
                TradeType = 1,
                PaymentId = paymentModel.Id,
                PaymentType = paymentModel.Payment.Type == 0 ? (byte)1 : (byte)0,
                PaymentTitle = paymentModel.Title,
                PaymentAmount = modelDto.Amount,
                AddTime = DateTime.Now,
                Recharges = rechargeList
            };
            //保存到数据库
            await _context.Set<PaymentCollection>().AddAsync(model);
            await this.SaveAsync();

            return model;
        }

        /// <summary>
        /// 根据条件删除记录
        /// </summary>
        public async Task<bool> DeleteAsync(Expression<Func<MemberRecharge, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            //查找主表
            var list = await _context.Set<MemberRecharge>()
                .Include(x => x.Collection).Where(funcWhere).ToListAsync();
            if (list == null) return false;
            _context.Set<MemberRecharge>().RemoveRange(list);
            //提交执行删除
            return await this.SaveAsync();
        }
    }
}
